package com.tarena.lbs.basic.controller;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.pojo.param.TagUpdateParam;
import com.tarena.lbs.basic.pojo.po.TagLibraryPO;
import com.tarena.lbs.basic.pojo.query.TagQuery;
import com.tarena.lbs.basic.pojo.vo.TagLibraryVO;
import com.tarena.lbs.basic.pojo.vo.TagVO;
import com.tarena.lbs.basic.service.TagService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 与标签有关的业务接口
 */
@Slf4j
@Tag(name = "标签数据管理")
@RestController
public class TagController {

    @Autowired
    private TagService tagService;


    @Operation(summary = "文章标签")
    @GetMapping("/basic/tagLibrary/info/article/tags")
    public Result<Map<String, List<TagVO>>> getArticleTags(){
        Map<String,List<TagVO>> tags = tagService.getTagsByType(0);
        return new Result<>(tags);
    }

    //用户标签 和文章标签数据结构 查询逻辑完全相同 只是入参传递的是tag_type=1

    @Operation(summary = "用户标签")
    @GetMapping("/basic/tagLibrary/info/userList")
    public Result<Map<String, List<TagVO>>> getUserTags(){
        //考虑 既然标签结构 文章和用户相同 后续还会查询用户标签 tagType=0|1
        Map<String,List<TagVO>> tags = tagService.getTagsByType(1);
        return new Result<>(tags);
    }

    //给人群创建时,提供的标签可选数据

    @Operation(summary = "人群标签可选数据")
    @GetMapping("/basic/tagLibrary/info/user/tags")
    public Result<Map<String, List<TagVO>>> getGroupTags(){
        Map<String,List<TagVO>> tags = tagService.getTagsByType(1);
        return new Result<>(tags);
    }
@Operation(summary = "根据ID获取标签")
@GetMapping("/basic/tagLibrary/info/tag/detail/{id}")
public Result<TagLibraryVO> getTagById(@PathVariable Integer id){
    TagLibraryPO tagLibraryPO = tagService.getTagById(id);
    if (tagLibraryPO == null) {
        return Result.fail("-1", "标签不存在");
    }
    TagLibraryVO vo = new TagLibraryVO();
    BeanUtils.copyProperties(tagLibraryPO, vo);
    return new Result<>(vo);
}

    @Operation(summary = "获取所有标签")
    @PostMapping("/basic/tagLibrary/info/tag/all")
    public Result<PageResult<TagLibraryVO>> getAllTags(@RequestBody TagQuery query) {
        PageResult<TagLibraryVO> voPage = tagService.getAllTags(query);
        return new Result<>(voPage);
    }

    @Operation(summary = "添加标签（包含分组和门店状态）")
    @PostMapping(value = "/basic/tagLibrary/info/tag/add")
    public Result addTag (
            @RequestParam Integer tagType,
            @RequestParam String tagName,
            @RequestParam(required = false) Integer tagParentId,
            @RequestParam(required = false) String coding,
            @RequestParam(required = false) String tagDesc,
            @RequestParam(required = false, defaultValue = "0") Integer status,
            @RequestParam(required = false, defaultValue = "0") Integer storeStatus) {
    
        try {
            // 参数校验
            if (tagName == null || tagName.trim().isEmpty() || tagType == null) {
                return Result.fail("-1", "标签名称和类型不能为空");
            }
    
            // 创建TagLibraryPO对象
            TagLibraryPO tagLibraryPO = new TagLibraryPO();
            tagLibraryPO.setTagType(tagType);
            tagLibraryPO.setTagName(tagName);
            tagLibraryPO.setTagParentId(tagParentId);
            tagLibraryPO.setCoding(coding);
            tagLibraryPO.setTagDesc(tagDesc);
            tagLibraryPO.setStatus(status);
            tagLibraryPO.setStoreStatus(storeStatus);
    
            boolean result = tagService.addTag(tagLibraryPO);
            return result ? Result.success() : Result.fail("-1", "新增标签失败");
        } catch (BusinessException e) {
            return Result.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("新增标签异常", e);
            return Result.fail("-1", "系统内部错误，请稍后重试");
        }
    }


    @Operation(summary = "更新标签")
    @PostMapping("/basic/tagLibrary/info/tag/update")
    public Result<Boolean> updateTag(@RequestBody TagUpdateParam param) {
        log.info("开始更新标签，参数：{}", param);
        try {
            boolean result = tagService.updateTag(param);
            log.info("标签更新{}", result ? "成功" : "失败");
            return new Result<>(result);
        } catch (BusinessException e) {
            log.warn("业务异常: {}", e.getMessage());
            return Result.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("更新标签异常", e);
            return Result.fail("-1", "系统内部错误，请稍后重试");
        }
    }

    @Operation(summary = "删除标签")
    @PostMapping("/basic/tagLibrary/info/tag/delete")
    public Result<Void> deleteTag(@RequestParam("id") Integer id) {
        log.info("删除标签,id:{}", id);
        try {
            //参数校验
            if (id == null || id <= 0){
                return Result.fail("-1","标签ID不能为空");
            }
            //调用服务层执行删除
            return tagService.deleteTag(id);
        } catch (Exception e) {
            log.error("删除标签异常", e);
            return Result.fail("-1", "系统内部错误，请稍后重试");
        }
    }


//    @Operation(summary = "删除标签")
//    @PostMapping("/basic/tagLibrary/info/tag/delete")
//    public Result<Void> delete(@RequestParam("id") Integer id) throws BusinessException{
//        log.info("删除标签,id:{}",id);
//        //参数校验
//        if (id == null || id <= 0){
//            return Result.fail("-1","标签ID不能为空");
//        }
//        //调用服务层执行删除
//        return tagService.deleteTag(id);
//    }

    @Operation(summary = "根据父标签ID获取子标签")
    @GetMapping("/basic/tagLibrary/info/tag/children/{parentId}")
    public Result<List<TagLibraryPO>> getTagsByParentId(@PathVariable Integer parentId){
        List<TagLibraryPO> tags = tagService.getTagsByParentId(parentId);
        return new Result<>(tags);
    }

    @Operation(summary = "启用/禁用标签")
    @PostMapping("/basic/tagLibrary/info/tag/status")
    public Result<Void> updateTagStatus(
            @RequestParam Integer id,
            @RequestParam Integer status) {
        try {
            // 参数校验
            if (id == null || id <= 0) {
                return Result.fail("-1", "标签ID不能为空");
            }
            if (status != 0 && status != 1) {
                return Result.fail("-1", "状态值必须为0(启用)或1(禁用)");
            }
            
            // 创建TagLibraryPO对象
            TagLibraryPO tagLibraryPO = new TagLibraryPO();
            tagLibraryPO.setId(id);
            tagLibraryPO.setStatus(status);
            tagLibraryPO.setUpdateAt(new Date());
            
            // 调用服务层更新状态
            boolean result = tagService.updateTag(tagLibraryPO);
            return result ? Result.success() : Result.fail("-1", "更新标签状态失败");
        } catch (Exception e) {
            log.error("更新标签状态异常", e);
            return Result.fail("-1", "系统内部错误，请稍后重试");
        }
    }
}